package com.newer.utils;

import com.newer.dao.bean.sys.Menu;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.*;

/**
 * 菜单信息转换类
 * <p>
 * Created by 寻添俊 on 2016/12/13.
 */
public class ConvertMenuUtils {

    /**
     * 菜单信息转换(二叉树用法)
     *
     * @param menus
     * @param parentId
     * @return
     */
    public static List<Menu> convertMenus(List<Menu> menus, String parentId) {
        List<Menu> result = new LinkedList<>();
        Map<String, Menu> menuMap = new LinkedHashMap<>();
        for (Menu menu : menus) {
            menuMap.put(menu.getId(), menu);
        }
        boolean isRootElement = false;
        for (Map.Entry<String, Menu> entry : menuMap.entrySet()) {
            Menu menu = entry.getValue();
            if (!isRootElement) {
                if (StringUtils.equals(menu.getId(), parentId)) {
                    //顶级节点
                    result.clear();
                    result.add(menu);
                    isRootElement = true;
                }
            }
            if (!isRootElement && StringUtils.equals(menu.getPid(), parentId)) {
                //顶级节点
                result.add(menu);
            } else {
                Menu parent = menuMap.get(menu.getPid());
                if (parent != null) {
                    if (CollectionUtils.isEmpty(parent.getMenus())) {
                        parent.setMenus(new LinkedList<>());
                    }
                    parent.getMenus().add(menu);
                }
            }
        }
        return result;
    }

    /**
     * 菜单信息转换(递归用法)
     *
     * @param menus
     * @param parentId
     * @return
     */
    public static List<Menu> converMenusRecurrence(List<Menu> menus, String parentId) {
        List<Menu> results = new ArrayList<>();
        for (Menu menu : menus) {
            String menuId = menu.getId();
            String pid = menu.getPid();
            if (StringUtils.equals(pid, parentId)) {
                // 递归方法,需要注意死循环
                List<Menu> childMenus = converMenusRecurrence(menus, menuId);
                menu.setMenus(childMenus);
                results.add(menu);
            }
        }
        return results;
    }
}
